package day11;

import java.util.concurrent.locks.ReentrantLock;

//通过Lock实现死锁
public class TestDeadLock2 {
    ReentrantLock lock1 = new ReentrantLock();
    ReentrantLock lock2 = new ReentrantLock();

    public void test1() {
        lock1.lock();
        System.out.println("线程1获取lock1的锁,等待lock2");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock2.lock();
        System.out.println("线程1获取lock1和的lock2锁");
        lock2.unlock();
        System.out.println("线程1释放了lock2的锁");
        lock1.unlock();
        System.out.println("线程1释放了lock1和lock2的锁");
    }

    public void test2() {
        lock2.lock();
        System.out.println("线程2获取lock2的锁,等待lock1");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock1.lock();
        System.out.println("线程2获取lock1和的lock2锁");
        lock1.unlock();
        System.out.println("线程2释放了lock1的锁");
        lock2.unlock();
        System.out.println("线程2释放了lock1和lock2的锁");
    }

    public static void main(String[] args) {
        TestDeadLock2 tdl = new TestDeadLock2();
        new Thread(()->{
            tdl.test1();
        }).start();
        new Thread(()->{
            tdl.test2();
        }).start();
    }
}
